//
//  MoRenPersonVC.m
//  EnterpriseEdition
//
//  Created by ypj on 2021/10/9.
//

#import "MoRenPersonVC.h"
#import "MoRenListCell.h"
#import "AddMoRenPersonView.h"
#import "MoRenLianXiRenModel.h"
@interface MoRenPersonVC ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>
@property (nonatomic,strong)  UITableView       *  tableView;
@property (nonatomic, strong) NSMutableArray    *  dataAry;
@property (nonatomic, assign) NSInteger            nowPage;
@property (nonatomic, assign) NSInteger            totalPage;
@property (nonatomic,strong) AddMoRenPersonView  *  addView;
@property (nonatomic,strong) AddMoRenPersonView  *  eduitView;
@property (nonatomic,strong) AddMoRenPersonView  *  deleteView;
@end

@implementation MoRenPersonVC

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
 
}

- (void)viewDidLoad {
     [super viewDidLoad];
     [self getLianXiRen];
     self.view.backgroundColor = White_Color;
    [self layoutCustomNav:self.view title:@"默认联系人"];
    [self createRightButtonItem];
    [self dataAry];
     self.userInfo=[YLUserMgr fetchUser];
    [self createTableView];
    MJRefreshNormalHeader * header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
       [self getLianXiRen];
    }];
    header.lastUpdatedTimeLabel.hidden = YES;
    self.tableView.mj_header = header;
}

-(void)createTableView{
    self.tableView = [[UITableView  alloc] initWithFrame:CGRectMake(0, kViewTopHeight, ScreenWidth, self.view.height - LL_TabbarSafeBottomMargin)];
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    self.tableView.emptyDataSetSource = self;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor=[UIColor whiteColor];
    [self.tableView registerNib:[UINib nibWithNibName:[MoRenListCell reuseIdentifier] bundle:nil] forCellReuseIdentifier:[MoRenListCell reuseIdentifier]];
    [self.view addSubview:self.tableView];
}
#pragma mark - ------------------ DZNEmptyData ------------------
-(UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView{
    return [UIImage imageNamed:@"No_order_icon"];
}
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *title = @"暂无数据";
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[UIFont systemFontOfSize:15.0f],
                                 NSForegroundColorAttributeName:gray666_color
                                 };
    return [[NSAttributedString alloc] initWithString:title attributes:attributes];
}
- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view {
    if (!self.tableView.mj_header.isRefreshing && !self.tableView.mj_footer.isRefreshing) {
        [self.tableView.mj_footer resetNoMoreData];
        self.nowPage = 1;
        [self getLianXiRen];
    }
}
- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    return -50;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  self.dataAry.count;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
     return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BD_WEAKSELF
    MoRenListCell  *cell=[tableView dequeueReusableCellWithIdentifier:[MoRenListCell reuseIdentifier]];
    if (!cell) {
        cell = [[MoRenListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[MoRenListCell reuseIdentifier]];
    }
    cell.selectionStyle= UITableViewCellSelectionStyleNone;
    MoRenLianXiRenModel *model = self.dataAry[indexPath.row];
    cell.nameLb.text = model.name;
    cell.phonelb.text = model.telePhone;
    if ([model.defaultFlag isEqualToString:@"1"]) {
        [cell.setBtn setImage:[UIImage imageNamed:@"openBtn"] forState:UIControlStateNormal];
        [cell.setBtn setTitle:@"当前默认联系人" forState:UIControlStateNormal];
        [cell.setBtn setTitleColor:ColorWith3C6CFC forState:UIControlStateNormal];
    } else {
        [cell.setBtn setTitle:@"设为默认" forState:UIControlStateNormal];
        [cell.setBtn setTitleColor:ColorWithAAAAAA forState:UIControlStateNormal];
        [cell.setBtn setImage:Image(@"closeBtn") forState:UIControlStateNormal];
    }
    [cell.setBtn whenTapped:^{
        if ([model.defaultFlag isEqualToString:@"1"]) return;
        [Tool showAlertTitle:@"确定修改默认联系人?" msg:@"" cancelTitle:@"取消" commitBtnTitle:@"修改" cancelHandlerBlock:^{
        } commitHandlerBlock:^{
            NSMutableDictionary *params = [NSMutableDictionary dictionary];
           [params setObject:@"1" forKey:@"defaultFlag"];
           [params setObject:@"edit" forKey:@"oper"];
            [params setObject:model.telePhone forKey:@"telePhone"];
            [params setObject:model.name forKey:@"name"];
           [params setObject:model.ID forKey:@"id"];
            [self addPerson:params withType:@"set" WithView:nil];
        } onVC:self];


    }];
    [cell.eduitLb whenTapped:^{
        BD_WEAKSELF
        UIWindow  *currentWindow=[BaseViewController getCurrentWindow];
        __weak AddMoRenPersonView *view =[AddMoRenPersonView shareInstance];
        view.frame=CGRectMake(0, 0, ScreenWidth, B_HEIGHT);
        view.viewTitle.text = @"修改联系人";
        view.nameTF.text = model.name;
        view.phoneTF.text = model.telePhone;
        [view setCurrentValueBlock:^(NSString * _Nonnull nameString, NSString * _Nonnull phoneString) {
            NSMutableDictionary *params=[NSMutableDictionary dictionary];
            [params setObject:nameString forKey:@"name"];
            [params setObject:phoneString forKey:@"telePhone"];
            [params setObject:@"edit" forKey:@"oper"];
            [params setObject:model.ID forKey:@"id"];
            [params setObject:model.defaultFlag forKey:@"defaultFlag"];
            [weakSelf addPerson:params withType:@"edit" WithView:view];
           
        }];
        [currentWindow addSubview:view];
        
        [view.popBtn whenTapped:^{
            [view removeFromSuperview];
        }];
    }];
    [cell.delectLb whenTapped:^{
        
        [Tool showAlertTitle:@"温馨提示" msg:@"确认删除当前联系人?" cancelTitle:@"取消" commitBtnTitle:@"确认" cancelHandlerBlock:^{
            
        } commitHandlerBlock:^{
            NSMutableDictionary *params=[NSMutableDictionary dictionary];
           [params setObject:@"del" forKey:@"oper"];
           [params setObject:model.ID forKey:@"id"];
           [weakSelf addPerson:params withType:@"del" WithView:nil];
        } onVC:self];
        
    }];
    return cell;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
        return [MoRenListCell cellHeight];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
   
}

#pragma mark ----------------<#note#>----------------
- (NSMutableArray *)dataAry {
    if (!_dataAry) {
        self.dataAry = [@[] mutableCopy];
    }
    return _dataAry;
}
-(void)createRightButtonItem{
    
//    UIButton *eduitButton = [UIButton buttonWithType:UIButtonTypeCustom];
//     eduitButton.frame=CGRectMake(ScreenWidth-45,  self.customerTitleLabel.top, 30, 30);
//    [eduitButton setImage:Image(@"AddPerson_icon") forState:UIControlStateNormal];
//    [eduitButton addTarget:self action:@selector(EduitButtonClick) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *eduitButton=[UIButton buttonWithType:UIButtonTypeCustom];
     eduitButton.frame=CGRectMake(ScreenWidth-75,  KStatuesBarHeight, 60, 30);
    eduitButton.backgroundColor = ColorWith3C6CFC;
    [eduitButton setTitle:@"添加" forState:UIControlStateNormal];
    [eduitButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    eduitButton.titleLabel.font = [UIFont systemFontOfSize:13];
    [eduitButton addTarget:self action:@selector(addPersonClick) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:eduitButton];
}
-(void)addPersonClick{
    BD_WEAKSELF
    UIWindow  *currentWindow=[BaseViewController getCurrentWindow];
    __weak AddMoRenPersonView *view =[AddMoRenPersonView shareInstance];
    view.frame=CGRectMake(0, 0, ScreenWidth, B_HEIGHT);
    [view setCurrentValueBlock:^(NSString * _Nonnull nameString, NSString * _Nonnull phoneString) {
        
        NSMutableDictionary  *  params=[NSMutableDictionary dictionary];
        [params setObject:nameString forKey:@"name"];
        [params setObject:phoneString forKey:@"telePhone"];
        [params setObject:@"add" forKey:@"oper"];
        [params setObject:@"0" forKey:@"defaultFlag"];
        [weakSelf addPerson:params withType:@"add" WithView:view];
       
    }];
    [currentWindow addSubview:view];
    
    [view.popBtn whenTapped:^{
        [view removeFromSuperview];
    }];
    
}

///添加联系人
-(void)addPerson:(NSMutableDictionary *)params withType:(NSString *)typeString WithView:(nullable AddMoRenPersonView *)view{
    NSString *url;
    if ([typeString isEqualToString:@"edit"] ||
        [typeString isEqualToString:@"set"]) {
        url = Edit_Contact_Url;
    }else if([typeString isEqualToString:@"add"]){
        url = Add_Contact_Url;
    }else if ([typeString isEqualToString:@"del"]){
        url = Del_Contact_Url;
    }
    
    [MSNetworkManager postRevertUrl:url params:params success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
        
        if (isSuccess) {
            if ([typeString isEqualToString:@"add"]){
                showAlert(@"添加成功");
            }else if ([typeString isEqualToString:@"edit"]){
                showAlert(@"编辑成功");
            }else if([typeString isEqualToString:@"del"]){
                showAlert(@"删除成功");
            } else {
                showAlert(@"设置成功");
            }
            [view removeFromSuperview];
        }
        [self getLianXiRen];
        
    } failure:^(NSUInteger code, NSString * _Nonnull message) {
    } withShowHud:YES];
    
 

}
-(void)getLianXiRen{
    
    [MSNetworkManager postRevertUrl:Get_Contact_Url params:@{} success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
        
        if(isSuccess){
            NSArray *cacheArray = resonseObj;
            self.dataAry = [MoRenLianXiRenModel  mj_objectArrayWithKeyValuesArray:cacheArray];
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
            [self.tableView reloadData];
        }
        
    } failure:^(NSUInteger code, NSString * _Nonnull message) {
        
    } withShowHud:NO];
    

}

@end
